#!/usr/bin/env python3
#-*-coding:utf-8-*-
import os
import sys

def prepare():
	#切换目录至/data
	os.chdir('/data')
	#安装依赖包
	cmd = "yum install -y gcc gcc-c++ zlib zlib-devel openssl openssl-devel pcre pcre-devel"
	os.system(cmd)
	
	#下载nginx源码包，默认版本为1.12.2
	cmd = "curl -O http://nginx.org/download/nginx-1.12.2.tar.gz"
	res = os.system(cmd)
	if res != 0:
		print("源码包下载失败，请重试")
		sys.exit(1)

	#解压
	cmd = "tar -xzvf nginx-1.12.2.tar.gz"
	res = os.system(cmd)
	if res != 0:
		print("解压失败，请删除源码包后重试")
		sys.exit(1)
	#创建nginx组，用户
	cmd = "groupadd nginx"
	os.system(cmd)
	
	cmd = "useradd -s /sbin/nologin -M -g nginx nginx"
	os.system(cmd)

def install():
	#编译
	code_path = '/data/nginx-1.12.2'
	install_path = '/data/nginx/'
	os.chdir(code_path)
	cmd = "./configure --user=nginx --group=nginx --prefix=/data/nginx --with-http_stub_status_module --with-http_gzip_static_module --with-http_realip_module --with-http_ssl_module --with-ipv6"
	res = os.system(cmd)
	if res != 0:
		print("nginx configure err")
		sys.exit(1)
	#安装
	cpu_num = 'cat /proc/cpuinfo |grep "processor" |uniq |wc -l'
	res = os.popen(cpu_num).read().strip("\n")
	cmd = 'make -j {}'.format(res)
	res = os.system(cmd)
	if res != 0:
		print("nginx make err")
		sys.exit(1)
	cmd = "make install"
	res = os.system(cmd)
	if res != 0:
		print("nginx install err")
		sys.exit(1)
	#创建 proxy_conf 目录
	os.mkdir('/data/nginx/proxy_conf', 0755)
	cmd = "chown nginx.root /data/nginx/proxy_conf"
	res = os.system(cmd)
	if res != 0:
		print("Directory creation failed")
		sys.exit(1)	
def config():
	f = open("/data/nginx/conf/nginx-reference.conf", mode="w")
	f.write("""user  nginx nginx;
worker_processes auto;
worker_rlimit_nofile 65535;

error_log  logs/error.log;
pid        logs/nginx.pid;

events {
    worker_connections  65535;
    use	epoll;
}

http {
    include       mime.types;
    include       /data/nginx/proxy_conf/*;
    default_type  application/octet-stream;
    client_header_buffer_size 16k;
    client_max_body_size 512m;
    client_body_timeout 10s;
    client_header_timeout 5s;
    large_client_header_buffers 4 64k;
    open_file_cache max=65535 inactive=20s;
    open_file_cache_min_uses 1;
    open_file_cache_valid 30s;
    proxy_redirect off;     
    #proxy_set_header Host $http_host;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_connect_timeout 90;
    proxy_send_timeout 90;
    proxy_read_timeout 90;
    proxy_buffer_size 16k;
    proxy_buffers 4 64k;
    proxy_busy_buffers_size 128k;
    proxy_temp_file_write_size 128k;
    proxy_cache_path /data/nginx/proxy_cache levels=1:2
    keys_zone=http-cache:1024m max_size=5g inactive=2d;
    proxy_temp_path /data/nginx/proxy_cache/tmp;
    map $http_x_forwarded_for $clientRealIp {
        "" $remote_addr;
        ~^(?P<firstAddr>[0-9\.]+),?.*$ $firstAddr;
     }
    log_format nginx_log_json '{"accessip_list":"$proxy_add_x_forwarded_for","client_ip":"$clientRealIp","http_host":"$host","@timestamp":"$time_iso8601","method":"$request_method","url":"$request_uri","status":"$status","http_referer":"$http_referer","body_bytes_sent":"$body_bytes_sent","request_time":"$request_time","http_user_agent":"$http_user_agent","total_bytes_sent":"$bytes_sent","server_ip":"$server_addr"}';
    access_log  logs/access.log  nginx_log_json;
    server_names_hash_bucket_size 128;

    #log_format  main  '$http_host [$time_local] "$request" $request_length '
    #                  '$status $body_bytes_sent $request_time "$http_referer" '
    #                  '"$http_user_agent"';
    sendfile        on;
    tcp_nopush     on;
    keepalive_timeout  65;

    gzip  on;
    gzip_min_length 1k;
    gzip_buffers 4 16k;
    gzip_comp_level 2;
    gzip_types text/plain application/x-javascript text/css application/xml text/javascript application/x-httpd-php image/jpeg 
    gzip_vary on;
    gzip_disable "MSIE [1-6]\.";
    
    server {
        listen       80;
        server_name  localhost;

        #charset koi8-r;

        #access_log  logs/host.access.log  main;

        location / {
            root   html;
            index  index.html index.htm;
        }
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }
    }
}""")
	f.close()

if __name__ == "__main__":
	prepare()
	install()
	config()
	print("nginx-1.12.2已安装完成...")
	print("nginx安装目录: /data/nginx")
	print("nginx日志目录: /data/nginx/logs")
	print("nginx启动方式：/data/nginx/sbin/nginx")
